package com.cqjtu.mycalculator;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener {
    //菜单开关标志
    private boolean flag = true;
    //音乐开关标志
    private boolean music_flag = true;
    //夜间模式开关标志
    private boolean night_flag = false;
    private  LinearLayout view_view;
    private LinearLayout view_parent;
    private LinearLayout main_layout;
    private Button erjinzhi;
    private Button bajinzhi;
    private Button shijinzhi;
    private Button shiliujinzhi;
    private Button baifenhao;
    private Button C;
    //声明一个Soundpool
    private SoundPool sp;
    //sound ID

    HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();

    private Button one;
    private Button two;
    private Button three;
    private Button four;
    private Button five;
    private Button six;
    private Button seven;
    private Button eight;
    private Button nine;
    private Button zero;
    private Button plus;
    private Button minus;
    private Button multiply;
    private Button divide;
    private Button point;
    private Button equal;

    private TextView display1;
    private TextView display2;
    private TextView display3;
    private TextView display4;
    private TextView note1;
    private TextView center;
    private TextView note2;
    private EditText result;
    private BigDecimal op1;
    private BigDecimal op2;
    private TextView deng;
    private Switch night;
    private Button clear;
    private boolean next;
    private Point size;
    private ImageView image_b;
    //image ID
    private int[] res = { R.id.image_view_b, R.id.image_view_c, R.id.image_view_e };
    private List<ImageView> imageViewList  = new ArrayList<ImageView>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

    }
    //动态设置跑马灯效果
    public static void setTextMarquee(TextView textView) {
        if (textView != null) {
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
        }
    }

    //获取屏幕分辨率，以适应各种大小屏幕
    public static Point getSize(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }

    //进制转换
    public static String translate(String str) throws Exception {
        char[] jin = { 'A', 'B', 'C', 'D', 'E','F'};
        StringBuilder stringBuilder;
        if(str.contains(".")){

            // 整数部分的值
            int in = Integer.valueOf(str.substring(0,str.indexOf(".")));
            // 小数部分的值
            DecimalFormat    df   = new DecimalFormat("0.0000000000");
            double r = Double.valueOf(df.format(Double.valueOf(str)-in));

            Log.i("mainActivity", r+"");
             stringBuilder = new StringBuilder();
            // 将整数部分转化为二进制
            int remainder = 0;
            int quotient = 0;
            while (in != 0) {
                // 得商
                quotient = in / 2;
                // 得余数
                remainder = in % 2;
                stringBuilder.append(remainder);
                in = quotient;
            }
            stringBuilder.reverse();

            stringBuilder.append(".");

            // 将小数部分转化为二进制
            int count = 32; // 限制小数部分位数最多为32位，如果超过32为则抛出异常
            double num = 0;
            while (r > 0.0000000001) {
                count--;
                num = r * 2;
                if (num >= 1) {
                    stringBuilder.append(1);
                    r = num - 1;
                } else {
                    stringBuilder.append(0);

                }
            }

        }else {  //为整数

            // 整数部分的值
            int in = Integer.valueOf(str);

             stringBuilder = new StringBuilder();
            // 将整数部分转化为二进制
            int remainder = 0;
            int quotient = 0;
            while (in != 0) {
                // 得商
                quotient = in / 2;
                // 得余数
                remainder = in % 2;
                stringBuilder.append(remainder);
                in = quotient;
            }
            stringBuilder.reverse();

        }

        Log.i("mainActivity", stringBuilder.toString());

        return stringBuilder.toString();
    }

    private void init() {

        size = getSize(this);
        view_view = (LinearLayout) findViewById(R.id.view_view);
        view_parent = (LinearLayout) findViewById(R.id.viewParent_layout);
        main_layout = (LinearLayout) findViewById(R.id.main_layout);
        erjinzhi = (Button) findViewById(R.id.erjinzhi);
        bajinzhi = (Button) findViewById(R.id.bajinzhi);
        shijinzhi = (Button)findViewById(R.id.shijinzhi);
        shiliujinzhi = (Button) findViewById(R.id.shiliujinzhi);
        baifenhao = (Button) findViewById(R.id.baifenhao);
        C = (Button) findViewById(R.id.C);

        one = (Button) findViewById(R.id.one);
        two = (Button) findViewById(R.id.two);
        three = (Button) findViewById(R.id.three);
        four = (Button) findViewById(R.id.four);
        five = (Button) findViewById(R.id.five);
        six = (Button) findViewById(R.id.six);
        seven = (Button) findViewById(R.id.seven);
        eight = (Button) findViewById(R.id.eight);
        nine = (Button) findViewById(R.id.nine);
        zero = (Button) findViewById(R.id.zero);
        plus = (Button) findViewById(R.id.plus);
        minus = (Button) findViewById(R.id.minus);
        multiply = (Button) findViewById(R.id.multiply);
        divide = (Button) findViewById(R.id.divide);
        point = (Button) findViewById(R.id.point);
        equal = (Button) findViewById(R.id.equal);
        display1 = (TextView) findViewById(R.id.display1);
        display2 = (TextView) findViewById(R.id.display2);
        display3 = (TextView) findViewById(R.id.display3);
        display4 = (TextView) findViewById(R.id.display4);
        note1 = (TextView) findViewById(R.id.note1);
        center = (TextView) findViewById(R.id.center);
        note2 = (TextView) findViewById(R.id.note2);
        deng = (TextView) findViewById(R.id.deng);
        result = (EditText) findViewById(R.id.result);
       // night = (Switch) findViewById(R.id.night);
        clear = (Button) findViewById(R.id.clear);

        erjinzhi.setOnClickListener(this);
        bajinzhi.setOnClickListener(this);
        shijinzhi.setOnClickListener(this);
        shiliujinzhi.setOnClickListener(this);
        baifenhao.setOnClickListener(this);
        C.setOnClickListener(this);

        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);
        five.setOnClickListener(this);
        six.setOnClickListener(this);
        seven.setOnClickListener(this);
        eight.setOnClickListener(this);
        nine.setOnClickListener(this);
        zero.setOnClickListener(this);
        plus.setOnClickListener(this);
        minus.setOnClickListener(this);
        multiply.setOnClickListener(this);
        divide.setOnClickListener(this);
        point.setOnClickListener(this);
        equal.setOnClickListener(this);
        clear.setOnClickListener(this);

        musicIni();

        result.setText("");

        image_b = (ImageView) findViewById(res[0]);
        for (int i = 0; i < res.length ; i++) {
            ImageView imageView = (ImageView) findViewById(res[i]);
            imageView.setOnClickListener(this);
            imageViewList.add(imageView);
        }





    }

    private void musicIni() {
        sp = new SoundPool(10, AudioManager.STREAM_SYSTEM,5);


        soundMap.put(0, sp.load(this, R.raw.zero, 1));
        soundMap.put(1, sp.load(this, R.raw.one, 1));
        soundMap.put(2, sp.load(this, R.raw.two, 1));
        soundMap.put(3, sp.load(this, R.raw.three, 1));
        soundMap.put(4, sp.load(this, R.raw.four, 1));
        soundMap.put(5, sp.load(this, R.raw.five, 1));
        soundMap.put(6, sp.load(this, R.raw.six, 1));
        soundMap.put(7, sp.load(this, R.raw.seven, 1));
        soundMap.put(8, sp.load(this, R.raw.eight, 1));
        soundMap.put(9, sp.load(this, R.raw.nine, 1));
        soundMap.put(11, sp.load(this, R.raw.media_11, 1));
        soundMap.put(12, sp.load(this, R.raw.media_12, 1));
        soundMap.put(13, sp.load(this, R.raw.media_13, 1));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.image_view_b:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(flag) {
                    startAnim();
                }else{
                    closeAnim();
                }
                break;

            case R.id.image_view_c:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(music_flag){
                    sp = null;
                    music_flag = false;
                }else {
                    musicIni();
                    music_flag = true;
                }
                break;

            case R.id.image_view_e:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!night_flag) {
                    main_layout.setBackgroundColor(Color.argb(255, 91, 84, 84));
                    night_flag = true;
                }
                else {
                    main_layout.setBackgroundColor(Color.WHITE);
                    night_flag = false;
                }
                break;

            case R.id.erjinzhi:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!result.getText().toString().equals("") && result.getText().toString().indexOf("-")==-1){
                    try {
                        display1.setText(translate(result.getText().toString()));
                        endOperation();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

            case R.id.bajinzhi:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!result.getText().toString().equals("") &&result.getText().toString().indexOf(".")==-1 && result.getText().toString().indexOf("-")==-1){
                    display1.setText(Integer.toOctalString(Integer.valueOf(result.getText().toString())).toUpperCase());
                    endOperation();
                }

                break;
            case R.id.shijinzhi:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!result.getText().toString().equals("") &&result.getText().toString().indexOf(".")==-1 && result.getText().toString().indexOf("-")==-1){
                    display1.setText((Integer.valueOf(result.getText().toString()))+"");
                    endOperation();
                }
                break;
            case  R.id.shiliujinzhi:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!result.getText().toString().equals("") && result.getText().toString().indexOf(".")==-1 && result.getText().toString().indexOf("-")==-1){
                        display1.setText(Integer.toHexString(Integer.valueOf(result.getText().toString())).toUpperCase());
                        endOperation();

                }
                break;

            case R.id.baifenhao:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if(!result.getText().toString().equals("")&& result.getText().toString()!=null){
                   if( result.getText().toString().indexOf(".")==-1){//没有小数点，则为整数
                       display1.setText(Integer.valueOf(result.getText().toString())/100f+"");
                       endOperation();
                   }else {
                       display1.setText(Double.valueOf(result.getText().toString())/100+"");
                       endOperation();
                   }
                }

                break;

            case R.id.C:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                String mStr = display1.getText().toString();
                if (!mStr.equals("")&&mStr!=null){
                    if(mStr.charAt(mStr.length()-1)!='+' && (mStr.charAt(mStr.length()-1)!='-'|| !center
                    .getText().toString().equals("-")) &&
                         mStr.charAt(mStr.length()-1)!='×' && mStr.charAt(mStr.length()-1)!='÷'){
                         display1.setText(display1.getText().toString().substring(0,mStr.length()-1));
                    }else{
                        center.setText("");
                        display1.setText(display1.getText().toString().substring(0,mStr.length()-1));
                        op1 = null;
                    }
                }
                break;

            case R.id.one:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);

                if (display1.getText().equals("0"))
                    display1.setText("1");
                else
                    display1.append("1");
                break;

            case R.id.two:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("2");
                else
                    display1.append("2");
                break;

            case R.id.three:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("3");
                else
                    display1.append("3");
                break;

            case R.id.four:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("4");
                else
                    display1.append("4");
                break;

            case R.id.five:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("5");
                else
                    display1.append("5");
                break;

            case R.id.six:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("6");
                else
                    display1.append("6");
                break;

            case R.id.seven:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("7");
                else
                    display1.append("7");
                break;

            case R.id.eight:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("8");
                else
                    display1.append("8");
                break;

            case R.id.nine:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("0"))
                    display1.setText("9");
                else
                    display1.append("9");
                break;

            case R.id.zero:

                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (!display1.getText().equals("0"))
                    display1.append("0");
                break;

            case R.id.plus:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (display1.getText().equals("")) {
                    display1.setText("+");
                    break;
                } else {
                    if (next) {
                        center.setText("");
                        next = false;
                    }
                    if (center.getText().equals("") && !display1.getText().toString().equals("")&&!display1.getText().toString().equals(".")) {
                        op1 = new BigDecimal(display1.getText().toString());
                        note1.setText(op1 + "");
                        center.setText("+");
                        display1.append("+");
                    }

                }
                break;

            case R.id.minus:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                String ll = display1.getText().toString();
                if (ll.equals("0") || ll.equals("") || ll==null)
                    display1.setText("-");
                else {
                    if (next) {
                        center.setText("");
                        next = false;
                    }
                    if (center.getText().equals("") && !ll.equals("")&&!ll.equals(".")) {
                        op1 = new BigDecimal(ll);
                        note1.setText(op1 + "");
                        display1.append("-");
                        center.setText("-");
                    }else if(op1 != null && (ll.lastIndexOf("-")<=ll.indexOf(center.getText()+""))){
                        display1.append("-");
                    }


                }
                break;

            case R.id.multiply:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (next) {
                    center.setText("");
                    next = false;
                }
                if (center.getText().equals("") && !display1.getText().toString().equals("")&&!display1.getText().toString().equals(".")) {
                    op1 = new BigDecimal(display1.getText().toString());
                    note1.setText(op1 + "");
                    display1.append("×");
                    center.setText("×");
                }

                break;

            case R.id.divide:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                if (next) {
                    center.setText("");
                    next = false;
                }
                if (center.getText().equals("") && !display1.getText().toString().equals("")&&!display1.getText().toString().equals(".")) {
                    op1 = new BigDecimal(display1.getText().toString());
                    note1.setText(op1 + "");
                    display1.append("÷");
                    center.setText("÷");
                }
                break;

            case R.id.point:
                if(sp!=null)
                    sp.play(soundMap.get(11),1,1,0,0,1);
                String l = display1.getText().toString();

                if (op1 == null && display1.getText().toString().indexOf(".") == -1)
                    display1.append(".");
                else if (op1 != null && (l.lastIndexOf(".")<=l.indexOf(center.getText()+"")))
                    display1.append(".");
                else if(op1 != null && display1.getText().toString().indexOf(".") == -1)
                    display1.append(".");

                break;

            case R.id.clear:
                if(sp!=null)
                    sp.play(soundMap.get(13),1,1,0,0,1);
                display1.setText("");
                display2.setText("");
                display3.setText("");
                display4.setText("");
                display1.setTextSize(50);
                display2.setTextSize(30);
                display3.setTextSize(30);
                display4.setTextSize(30);
                note1.setText("");
                note2.setText("");
                center.setText("");
                result.setText("");
                op1 = null;
                op2 = null;
                break;

            case R.id.equal:
                if(sp!=null)
                    sp.play(soundMap.get(12),1,1,0,0,1);

                if(op1==null&&op2==null){
                    if(display1.getText().toString()!=null&& !display1.getText().toString().equals("") && !display1.getText().toString().equals("."))
                    op1 = new BigDecimal(display1.getText().toString());
                    else break;
                }

                if (display1.getText().toString().indexOf("=") == -1) {
                    if (op1 != null || op2 != null) {
                        display1.append("=");
                        deng.setText(" = ");
                    }
                }

                String str = display1.getText().toString();
                if(center.getText().toString().equals("")){

                }
                else if ((str.lastIndexOf(center.getText().toString()) + 1) < str.indexOf("=")) {
                    if(!str.substring(str.lastIndexOf(center.getText().toString())+1,str.indexOf("=")).equals(".")) {
                        op2 = new BigDecimal(str.substring(str.lastIndexOf(center.getText().toString()) + 1, str.indexOf("=")));
                        note2.setText(op2 + "");
                    }
                }

                if (op2 == null && op1 != null) {
                    result.setText(op1.toString());
                    display1.append(op1.toString());
                } else if (op1 == null && op2 != null) {
                    result.setText(op2.toString());
                    display1.append(op2.toString());
                } else if (op1 == null && op2 == null) {

                } else {
                    switch (center.getText().toString()) {
                        case "+":
                            display1.append((op1.add(op2)) + "");
                            result.setText((op1.add(op2)) + "");
                            break;
                        case "-":
                            display1.append((op1.subtract(op2)) + "");
                            result.setText((op1.subtract(op2)) + "");
                            break;
                        case "×":
                            display1.append(op1.multiply(op2) + "");
                            result.setText((op1.multiply(op2)) + "");
                            break;
                        case "÷":
                            if (Math.abs(op2.doubleValue() - 0.0d) < 0.00000001) {
                                display1.append("error");
                                result.setText("error");
                            } else {
                                //String ss = new DecimalFormat("0.000000000000000").format(op1.doubleValue()/op2.doubleValue());
                                String ss = Double.valueOf(note1.getText().toString())/Double.valueOf(note2.getText().toString()) +"";
                                display1.append(ss);
                                result.setText(ss);
                            }
                            break;
                    }
                }

                endOperation();

                // center.setText("");
                break;
        }
    }




    //动画效果
    private void startAnim() {

        for (int i = 1; i < res.length; i++) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(imageViewList.get(i),
                    "translationX",0F,i*200);
            animator.setDuration(500);
            animator.start();
        }
        flag = false;

    }

    private void closeAnim() {
        for (int i = 1; i < res.length; i++) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(imageViewList.get(i),
                    "translationX",i*200,0F);
            animator.setDuration(500);
            animator.start();
        }
        flag = true;
    }

    private void endOperation() {
        setTextMarquee(display2);
        setTextMarquee(display3);
        setTextMarquee(display4);

        display4.setText(display3.getText());
        display3.setText(display2.getText());
        display2.setText(display1.getText());
        display1.setText("");
        next = true;
        //op2 = null;
        op1 = null;
    }
}
